﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace MvcClient.Controllers
{
    /// <summary>
    /// 示例
    /// </summary>
    [Route("[controller]")]
    //[Microsoft.AspNetCore.Authorization.Authorize(AuthenticationSchemes = "Cookies")]
    public class SampleController : Controller // System.Web.Http.ApiController
    {
        /// <summary>
        /// 获取当前服务器时间
        /// </summary>
        /// <returns></returns>
        [HttpGet("now")]
        [Microsoft.AspNetCore.Authorization.Authorize(AuthenticationSchemes = "Bearer")]
        public DateTime GetServerNow()
        {
            return DateTime.Now;
        }

        /// <summary>
        /// 生成Jwt
        /// </summary>
        /// <returns></returns>
        [Microsoft.AspNetCore.Authorization.Authorize(AuthenticationSchemes = "Cookies")]
        [HttpGet("jwt")]
        public string GenerateJwt()
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("387CF772-ED9D-405B-B294-1949DAA2C2FF"));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //身份
            var user = HttpContext.User;
            //令牌
            var expires = DateTime.Now.AddMinutes(1024);
            var token = new JwtSecurityToken(
                issuer: "myIssuer",
                audience: "myMvc",
                claims: user.Claims,
                notBefore: DateTime.Now,
                expires: expires,
                signingCredentials: credentials
                );
            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return jwtToken;
        }
    }
}
